<?php

namespace plugin\ycMassage\app\model;

use plugin\ycMassage\utils\enum\MoneyAction;
use think\Exception;
use think\facade\Db;

class MassageUserBill extends Model
{
    public static function increase($remarks, $uid, $moeny, $form_uid = null)
    {
        $MassageUserWallet = MassageUserWallet::where(['uid' => $uid])->lock(true)->find();
        if (!$MassageUserWallet) {
            throw new Exception('用户钱包不存在');
        }
        $model = new self();
        $model->uid = $uid;
        $model->form_uid = $form_uid;
        $model->saas_appid = $MassageUserWallet->saas_appid;
        $model->money = $moeny;
        $model->old_money = $MassageUserWallet->money;
        $model->new_money = $MassageUserWallet->money + $moeny;
        $model->action = MoneyAction::INCREASE['value'];
        $model->remarks = $remarks;
        $model->save();

        $MassageUserWallet->money = Db::raw('money+' . $moeny);
        $MassageUserWallet->money_sum = Db::raw('money_sum+' . $moeny);
        $MassageUserWallet->save();
    }
    public static function decrease($remarks, $uid, $moeny, $form_uid = null)
    {
        $MassageUserWallet = MassageUserWallet::where(['uid' => $uid])->lock(true)->find();
        if (!$MassageUserWallet) {
            throw new Exception('用户未开通钱包');
        }
        $moeny = abs($moeny);
        if ($MassageUserWallet->money < $moeny) {
            throw new \Exception('余额不足');
        }
        $model = new self();
        $model->uid = $uid;
        $model->form_uid = $form_uid;
        $model->saas_appid = $MassageUserWallet->saas_appid;
        $model->money = $moeny;
        $model->old_money = $MassageUserWallet->money;
        $model->new_money = $MassageUserWallet->money - $moeny;
        $model->action = MoneyAction::DECREASE['value'];
        $model->remarks = $remarks;
        $model->save();

        $MassageUserWallet->money = Db::raw('money-' . $moeny);
        $MassageUserWallet->save();
    }
}
